<template>
  <div class="user-list">
    <el-card>
      <div slot="header">
        <span>用户列表</span>
        <el-button style="float: right;" type="primary" @click="fetchUsers" aria-label="刷新用户列表" title="刷新用户列表">刷新</el-button>
      </div>
      <el-table :data="users" style="width: 100%" aria-label="用户列表" title="用户列表">
        <el-table-column prop="user_id" label="用户ID"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="nickname" label="昵称"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" aria-label="编辑用户" title="编辑用户">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)" aria-label="删除用户" title="删除用户">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { selectAllUser } from '@/services/user.js'

export default {
  name: 'UserList',
  data() {
    return {
      users: []
    }
  },
  mounted() {
    this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await selectAllUser()
        console.log('用户列表响应:', response)
        // 确保响应是数组格式，如果返回的是对象但包含数据数组，则提取该数组
        if (Array.isArray(response)) {
          this.users = response
        } else if (response && typeof response === 'object' && Array.isArray(response.data)) {
          this.users = response.data
        } else if (response && typeof response === 'object' && response.data && Array.isArray(response.data.data)) {
          this.users = response.data.data
        } else {
          this.users = []
        }
      } catch (error) {
        this.$message.error('获取用户列表失败')
      }
    },
    handleEdit(row) {
      // 处理编辑逻辑
      console.log('编辑用户:', row)
      this.$message.warning('编辑功能待实现')
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 实际项目中这里会调用API删除用户
        this.$message.success('删除成功')
        this.fetchUsers() // 刷新列表
      } catch (error) {
        // 用户取消删除或删除失败
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.user-list {
  padding: 20px;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  width: -webkit-fill-available;
  width: stretch;
}
</style>